package callLinuxCommand.callLinuxCommand;

import java.io.IOException;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public class LinuxConnection {

	public static Connection conn = null;
	public static Session session = null;

	public static Connection getConn(String hostname, String username, String password) {
		boolean isAuthenticated = false;

		try {
			conn = new Connection(hostname);
			conn.connect();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		try {
			isAuthenticated = conn.authenticateWithPassword(username, password);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (isAuthenticated == false) {
			return null;
		}
		return conn;

	}

	public static Session getSession(String hostname, String username, String password) {
		boolean isAuthenticated = false;

		try {
			if (conn == null) {
				conn = new Connection(hostname);
				conn.connect();
			}
			isAuthenticated = conn.authenticateWithPassword(username, password);
			if (session == null) {
				session = conn.openSession();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		if (isAuthenticated == false) {
			return null;
		}
		System.out.println("登录" + hostname + "成功!用户:" + username + " 密码" + password);
		return session;

	}

	public static void close() {
		if (conn != null) {
			System.out.println("关闭连接!");
			conn.close();
		}
		if (session != null) {
			System.out.println("关闭session!");
			session.close();
		}
	}

}
